package tech.yunland.shop.web;

import com.moyuer.bsf.common.Pagination;
import com.moyuer.bsf.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.yunland.shop.domain.model.Lessons;
import tech.yunland.shop.domain.service.LessonsService;
import tech.yunland.shop.domain.service.UserLessonsService;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * Created by v on 17-7-3.
 */
@RestController
@RequestMapping("/lessons")
public class LessonsController extends BaseController {

    @Autowired
    private LessonsService lessonsService;

    @Autowired
    private UserLessonsService userLessonsService;

    /**
     * 查询课程
     * @param param
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public Pagination<Lessons> get(@RequestParam(required = false) String param,
                                   @RequestParam(required = false) Integer page,
                                   @RequestParam(required = false) Integer rows) {
        Pagination result = new Pagination(page, rows);
        Integer startIdx = result.getStartIdx();
        Integer count = lessonsService.getSize(param);
        List<Map<String, Object>> records = lessonsService.get(param, startIdx, rows);
        result.setCount(count);
        result.setRecords(records);
        return result;
    }

    /**
     * 新增课程
     *
     * @param lessons
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public void save(@RequestBody @Valid Lessons lessons) {
        lessonsService.save(lessons);
    }

    /**
     * 学生查询已选课程
     * @param uid
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping(value = "/getLessons", method = RequestMethod.GET)
    public Pagination<Lessons> getLessons(@RequestParam(required = false) String uid,
                                          @RequestParam(required = false) Integer page,
                                          @RequestParam(required = false) Integer rows){
        if (uid == null) {
            uid = currentUserId;
        }
        Pagination result = new Pagination(page, rows);
        Integer startIdx = result.getStartIdx();
        Integer count = lessonsService.getLessonsSize(uid);
        List<Map<String, Object>> records = lessonsService.getLessons(uid, startIdx, rows);
        result.setCount(count);
        result.setRecords(records);
        return result;
    }

    /**
     * 学生设置课程
     *
     * @param uid
     * @param lids
     */
    @RequestMapping(value = "/choice", method = RequestMethod.POST)
    public void choice(@RequestParam(required = false) String uid,
                       @RequestParam(required = false) List<String> lids) {
        if (uid == null) {
            uid = currentUserId;
        }
        userLessonsService.choice(uid, lids);
    }
}
